/**
 * Copyright © 2022 SWAK Info.
 * File Name: SystemClock.java
 */
package com.swak.frame.context;

import java.util.Date;
import java.util.Optional;

/**
 * @ClassName: SystemClock.java
 * @author: colley.ma
 * @date: 2022/03/07
 */
public abstract class SystemClock {

    private static ThreadLocal<SystemClock> threadVar = new ThreadLocal<SystemClock>();
    private final Date nowTime;

    public SystemClock(Date nowTime) {
        this.nowTime = nowTime;
    }

    private static Date getNowTime() {
        SystemClock clock = threadVar.get();
        if (clock != null) {
            return clock.nowTime;
        }
        return null;
    }

    public static void set(Date nowTime) {
        threadVar.set(new SystemClock(nowTime) {});
    }

    public static void clear() {
        threadVar.set(null);
        threadVar.remove();
    }

    public static long currentTimeMillis() {
        Date nowTime = getNowTime();
        if (nowTime != null) {
            return nowTime.getTime();
        }
        return System.currentTimeMillis();

    }

    public static Date nowDate() {
        return Optional.ofNullable(getNowTime()).orElse(new Date());
    }

    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());
        System.out.println(SystemClock.currentTimeMillis());
        System.out.println(System.nanoTime());
    }
}
